package com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.YxyApiRespModel;

import io.swagger.annotations.ApiOperation;

/**
 * 下载试卷
 * 
 * 
 */
@RestController
@CrossOrigin
public class ZujuanPaperDownloadController extends YxyApiBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZujuanPaperDownloadController.class);

    @Value("${zujuan.storage.upload.paper}")
    private String downloadDir;

    @ApiOperation(value = "下载试卷")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/zujuan/paper/export", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void precess(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "filename", required = true) String filename) {
        // zip存放的路径
        String zipFilePath = downloadDir + getPath();
        // zip 存放的文件
        // String zipName = "下载试卷-2017-06-28-17-07-48";
        String zipName = filename;
        String realpath = zipFilePath + File.separator + zipName + ".docx";
        File zipfile = new File(realpath);

        LOGGER.info("读取文件路径为=============：" + realpath);
        // 获得二进制输入流
        FileInputStream fileInputStream = null;
        // 缓存区，二进制输入流
        BufferedInputStream bufferedInputStream = null;
        // 二进制输出流
        OutputStream outputStream = null;
        // 缓存区二进制输出流
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 写明要下载的文件的大小
            response.setContentLength((int) zipfile.length());
            // 文件名
            String downloadFilename = zipfile.getName();
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
            // 设置在下载框默认显示的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
            // 指明response的返回对象是文件流
            response.setContentType("application/octet-stream");
            // 编码格式
            response.setCharacterEncoding("UTF-8");
            // 每次读取字节数 1024 * 10
            byte[] b = new byte[1024 * 10];
            // 获取本地zip文件输入流
            fileInputStream = new FileInputStream(zipfile);
            bufferedInputStream = new BufferedInputStream(fileInputStream, b.length);
            // 获取输出流
            outputStream = response.getOutputStream();
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 每次读取字节数
            int length;
            while ((length = bufferedInputStream.read(b, 0, b.length)) != -1) {
                bufferedOutputStream.write(b, 0, length);
            }
            outputStream.flush();

        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
        } finally {
            // 关闭流
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
            }
        }
        return;
    }

    // 获取年月日路径
    private String getPath() {
        StringBuffer path = new StringBuffer("/");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Date date = c.getTime();
        String pathDate = sdf.format(date);
        String year = pathDate.toString().substring(0, 4);
        path.append(year + "/");
        String mouth = pathDate.toString().substring(5, 7);
        path.append(mouth + "/");
        String day = pathDate.toString().substring(8, 10);
        path.append(day);
        String pathString = path.toString();
        return pathString;
    }

    protected static class DownLoadRespModel extends YxyApiRespModel {

    }

}
